from django.shortcuts import render, redirect, HttpResponse, reverse
from crm import models
from crm.forms import CustomerForm, ConsultRecordForm, EnrollmentForm, PaymentRecord
from utils.pagenation import Pagination
from django.db import transaction
from django.conf import settings  # 这样导入时在settings中的配置需要大写
from .base import ShowList


# 展示用户
class CustomerList(ShowList):

    def get(self, request, *args, **kwargs):
        q = self.search(['qq', 'name', 'phone'])
        if request.path_info == reverse('crm:customer_list'):
            customers = models.Customer.objects.filter(q, consultant__isnull=True)
        else:
            customers = models.Customer.objects.filter(q, consultant=request.user_obj)
        page = Pagination(request.GET.get('page', 1), customers.count(), request.GET.copy(), 2)
        return render(request, 'consultant/customer_list.html',
                      {'customers': customers[page.start: page.end], 'page_html': page.page_html,
                       'url': reverse('crm:customer_list')})

    def multi_apply(self):
        pk_list = self.request.POST.getlist('pk')
        if len(pk_list) + models.Customer.objects.filter(
                consultant=self.request.user_obj).count() > settings.MAX_CUSTOMER_NUM:
            return HttpResponse('您的客户数量以达到上限')
        try:
            with transaction.atomic():
                queryset = models.Customer.objects.filter(pk__in=pk_list, consultant=None).select_for_update()  # 加行级锁
                if len(pk_list) != queryset.count():
                    return HttpResponse('客户已被其他销售选取')
                queryset.update(consultant=self.request.user_obj)
        except Exception:
            pass

    def multi_pub(self):
        pk_list = self.request.POST.getlist('pk')
        models.Customer.objects.filter(pk__in=pk_list).update(consultant=None)


# 编辑和增加客户
def customer_change(request, pk=None):
    form_obj = models.Customer.objects.filter(pk=pk).first()
    obj = CustomerForm(instance=form_obj)
    if request.method == 'POST':
        obj = CustomerForm(request.POST, instance=form_obj)
        if obj.is_valid():
            obj.save()
            next_url = request.GET.get('next')
            if next:
                return redirect(next_url)
            return redirect('crm:customer_list')
    title = '编辑客户' if pk else '添加客户'
    return render(request, 'form.html', {'obj': obj, 'title': title})


# 展示一个销售的所有客户跟进记录
class ConsultRecordList(ShowList):

    def get(self, request, customer_id=None, *args, **kwargs):
        q = self.search(['note', 'customer__name'])
        if customer_id:
            consult_records = models.ConsultRecord.objects.filter(q, customer_id=customer_id,
                                                                  customer__consultant=request.user_obj,
                                                                  delete_status=False)
        else:
            consult_records = models.ConsultRecord.objects.filter(q, consultant=request.user_obj, delete_status=False)
        page = Pagination(request.GET.get('page'), consult_records.count(), request.GET.copy(), 2)
        return render(request, 'consultant/consult_record_list.html',
                      {'consult_records': consult_records.order_by('-date')[page.start: page.end],
                       'page_html': page.page_html})


# 增加和编辑跟进记录
def consult_record_change(request, pk=None):
    form_obj = models.ConsultRecord.objects.filter(pk=pk).first()
    obj = ConsultRecordForm(request, instance=form_obj)
    if request.method == 'POST':
        obj = ConsultRecordForm(request, request.POST, instance=form_obj)
        if obj.is_valid():
            obj.save()
            next_url = request.GET.get('next')
            if next_url:
                return redirect(next_url)
            return redirect('crm:customer_record_list')
    title = '编辑跟进记录' if pk else '增加跟进记录'
    return render(request, 'form.html', {'obj': obj, 'title': title})


# 展示报名表
class EnrollmentList(ShowList):

    def get(self, request, customer_id=None, *args, **kwargs):
        if customer_id:
            enrollments = models.Enrollment.objects.filter(customer_id=customer_id)
        else:
            enrollments = models.Enrollment.objects.filter(customer__consultant=request.user_obj)
        page = Pagination(request.GET.get('page'), enrollments.count(), request.GET.copy(), 2)
        return render(request, 'consultant/enrollment_list.html',
                      {'enrollments': enrollments.order_by('-enrolled_date')[page.start: page.end],
                       'page_html': page.page_html})


# 增加和编辑报名表
def enrollment_change(request, pk=None, customer_id=None):
    form_obj = models.Enrollment(customer_id=customer_id) if customer_id else models.Enrollment.objects.filter(
        pk=pk).first()
    obj = EnrollmentForm(instance=form_obj)
    if request.method == 'POST':
        obj = EnrollmentForm(request.POST, instance=form_obj)
        if obj.is_valid():
            obj.save()
            next_url = request.GET.get('next')
            if next_url:
                return redirect(next_url)
            return redirect('crm:customer_record_list')
    title = '编辑报名表' if pk else '添加报名表'
    return render(request, 'form.html', {'obj': obj, 'title': title})


# 展示缴费记录表
class PaymentRecordList(ShowList):

    def get(self, request, customer_id=None, *args, **kwargs):
        if customer_id:
            payment_records = models.PaymentRecord.objects.filter(customer_id=customer_id,
                                                                  customer__consultant=request.user_obj)
        else:
            payment_records = models.PaymentRecord.objects.filter(consultant=request.user_obj)
        page = Pagination(request.GET.get('page'), payment_records.count(), request.GET.copy(), 2)
        return render(request, 'consultant/payment_record_list.html',
                      {'payment_records': payment_records.order_by('-date')[page.start: page.end],
                       'page_html': page.page_html})


# 增加和编辑消费记录
def payment_change(request, pk=None, customer_id=None):
    form_obj = models.PaymentRecord(customer_id=customer_id) if customer_id else models.PaymentRecord.objects.filter(
        pk=pk).first()
    obj = PaymentRecord(request, instance=form_obj)
    if request.method == 'POST':
        obj = PaymentRecord(request, request.POST, instance=form_obj)
        if obj.is_valid():
            obj.save()
            next_url = request.GET.get('next')
            if next_url:
                return redirect(next_url)
            return redirect('crm:payment_record_list')
    title = '编辑缴费表' if pk else '添加缴费表'
    return render(request, 'form.html', {'obj': obj, 'title': title})
